package com.ruoyi.web.controller.financial;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExcelUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.web.domain.financial.Financial;
import com.ruoyi.web.service.financial.IFinancialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 财务数据Controller
 *
 * @author ruoyi
 * @date 2023-07-24
 */
@RestController
@RequestMapping("/financial/financial")
public class FinancialController extends BaseController {
    
    @Autowired
    private IFinancialService financialService;
    
    /**
     * 导入财务数据
     */
    @PreAuthorize("@ss.hasPermi('financial:financial:import')")
    @Log(title = "财务管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        try {
            // 将 MultipartFile 转换为可标记的输入流
            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            
            ExcelUtil<Financial> util = new ExcelUtil<Financial>(Financial.class);
            List<Financial> financialList = util.importExcel(inputStream);
            String operName = getUsername();
            String message = financialService.importFinancial(financialList, operName);
            return success(message);
        } catch (Exception e) {
            log.error("导入失败：", e);
            return error("导入失败：" + e.getMessage());
        }
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<Financial> util = new ExcelUtil<Financial>(Financial.class);
        util.importTemplateExcel(response, "财务数据");
    }
} 